<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * this class user to do operations related to user.
 *
 * @author jianfeng
 */
class BAUserCooker extends BAEventCooker {
    /**
     * 这个函数添加用户个人信息，有以下几种情形需要考虑：
     * 1）用户输入的手机号已经被平台用户使用，那么，应该告诉用户重新使用别的手机号
     * 2）在机构中添加个人数据，都需要用这个函数来添加，来保证平台手机号和SPACE手机号的
     * 一致
     * 3）如果用户输入EMAIL，也需要确认EMAIL在平台数据里面的唯一性
     * 这个函数添加的逻辑是：
     * 1）如果平台个人数据和机构个人数据都不存在，那么，将先添加平台数据，同时添加机构数据
     * 2）如果平台数据已经存在，将检查提供的手机和电邮是否一致，不一致会报错，如果没有错误，添加机构数据
     * 如果添加的数据中有平台没有的数据，将同时添加到平台数据里面，平台已经有的数据项，只添加到机构数据
     * 3）如果已经有机构数据，没有平台数据，这个函数将不处理
     * @param type $userInfo
     * @return MIX,boolean,ARRAY OR BTREELIST OBJECT
     */
    /*
      public function addUserInfo($userInfo) {
      $spaceUserInfoTable = new BAUserSheet('userInfo');
      $userInfoTable = new BUserSheet('userInfo');
      $result = NULL;
      $error = new BAError();
      $myMobile = NULL;
      $myEmail = NULL;

      $user = Blyn::app()->getCurrentUser();
      $myMobileAttr = $user->getAttribute('userInfo.mobile');
      if ($myMobileAttr != NULL) {
      $myMobile = $myMobileAttr->getValue();
      }
      $myEmailAttr = $user->getAttribute('userInfo.email');
      if ($myEmailAttr != NULL) {
      $myEmail = $myEmailAttr->getValue();
      }

      if (is_array($userInfo) && $userInfo != NULL) {

      if (isset($userInfo['mobile'])) {
      if ($myMobile != NULL && $userInfo['mobile'] != $myMobile) {
      $error->addError('已经注册了手机号' . $myMobile . ',不能再用别的手机号！', 'wrongMobile');
      }
      }

      if (isset($userInfo['email'])) {
      if ($myEmail != NULL && $userInfo['email'] != $myEmail) {
      $error->addError('已经注册了EMAIL' . $myEmail . ',不能再用别的EMAIL！', 'wrongEmail');
      }
      }
      //首先检查是否已经存在手机和EMAIL号，如果已经存在，返回错误
      $existUserInfo = $this->haveExistUserInfo($userInfo);
      if ($existUserInfo != NULL) {//说明有已经存在的EMAIL或者MOBILE
      if (isset($existUserInfo['mobile']) && $existUserInfo['mobile'] != $myMobile) {
      $error->addError('手机号码已被使用！', 'wrongMobile');
      }
      if (isset($existUserInfo['email']) && $existUserInfo['email'] != $myEmail) {
      $error->addError('EMAIL已被使用！', 'wrongEmail');
      }
      }

      if ($error->haveErrors()) {
      return $error;
      }

      //查找当前用户的USERINFO
      $oUserInfo = $this->getUserInfo();

      if ($oUserInfo != NULL) {
      if ($myMobile != NULL || $myEmail != NULL) {
      //说明只是存在平台用户数据，用平台数据中的手机和EMAIL来加入
      //SPACE个人数据
      if ($myMobile != NULL)
      $userInfo['mobile'] = $myMobile;
      if ($myEmail != NULL)
      $userInfo['email'] = $myEmail;
      return $spaceUserInfoTable->addList($userInfo);
      } else {//说明SPACE和平台的个人数据都存在，而且返回SPACE的个人数据
      return $oUserInfo->addItems($userInfo);
      }
      } else {//说明平台个人数据和SPACE个人数据都不存在
      //分别添加平台个人数据和SPACE个人数据
      if (!isset($userInfo['mobile'])) {
      $error->addError('必须提供手机号！', 'wrongMobile');
      return $error;
      }
      $oUserInfo = NULL;
      $userInfoItems = array();
      $user = Blyn::app()->getCurrentUser();
      //添加平台个人数据
      $mobileAttr = Blyn::app()->getCurrentUser()->getAttribute('userInfo.mobile');
      if ($mobileAttr == NULL && isset($userInfo['mobile'])) {
      $user->addAttribute('userInfo.mobile', $userInfo['mobile']);
      $userInfoItems['mobile'] = $userInfo['mobile']; //也将数据加入平台用户数据表
      $oUserInfo = $userInfoTable->getList(array('itemData' => $userInfoItems));
      if ($oUserInfo == NULL) {
      $oUserInfo = $userInfoTable->addList($userInfoItems);
      }
      }
      $emailAttr = Blyn::app()->getCurrentUser()->getAttribute('userInfo.email');
      if ($emailAttr == NULL && isset($userInfo['email'])) {
      $user->addAttribute('userInfo.email', $userInfo['email']);
      $userInfoItems['email'] = $userInfo['email'];
      //只有当数据不存在时，才能添加个人数据，个人数据不能在这里更新
      if ($oUserInfo != NULL && $oUserInfo->getItem('email') == NULL) {
      $oUserInfo->addItem('email', $userInfo['email']);
      }
      }
      $familyNameAttr = Blyn::app()->getCurrentUser()->getAttribute('userInfo.familyName');
      if ($familyNameAttr == NULL && isset($userInfo['familyName'])) {
      $user->addAttribute('userInfo.familyName', $userInfo['familyName']);
      //只有当数据不存在时，才能添加个人数据，个人数据不能在这里更新
      if ($oUserInfo != NULL && $oUserInfo->getItem('familyName') == NULL) {
      $oUserInfo->addItem('familyName', $userInfo['familyName']);
      }
      }
      $surNameAttr = Blyn::app()->getCurrentUser()->getAttribute('userInfo.surName');
      if ($surNameAttr == NULL && isset($userInfo['surName'])) {
      $user->addAttribute('userInfo.surName', $userInfo['surName']);
      //只要当数据不存在时，才能添加个人数据，个人数据不能在这里更新
      if ($oUserInfo != NULL && $oUserInfo->getItem('surName') == NULL) {
      $oUserInfo->addItem('surName', $userInfo['surName']);
      }
      }
      $genderAttr = Blyn::app()->getCurrentUser()->getAttribute('userInfo.gender');
      if ($genderAttr == NULL && isset($userInfo['gender'])) {
      $user->addAttribute('userInfo.gender', $userInfo['gender']);
      //只要当数据不存在时，才能添加个人数据，个人数据不能在这里更新
      if ($oUserInfo != NULL && $oUserInfo->getItem('gender') == NULL) {
      $oUserInfo->addItem('gender', $userInfo['gender']);
      }
      }
      $birthAttr = Blyn::app()->getCurrentUser()->getAttribute('userInfo.birth');
      if ($birthAttr == NULL && isset($userInfo['birth'])) {
      $user->addAttribute('userInfo.birth', $userInfo['birth']);
      //只要当数据不存在时，才能添加个人数据，个人数据不能在这里更新
      if ($oUserInfo != NULL && $oUserInfo->getItem('birth') == NULL) {
      $oUserInfo->addItem('birth', $userInfo['birth']);
      }
      }

      //添加SPACE用户数据
      return $spaceUserInfoTable->addList($userInfo);
      }
      }

      return FALSE;
      }
     * 
     */

    /**
     * 这个函数将检查平台用户数据里面是否已经存在手机号和电邮，返回的数据是已经存在的
     * 手机号或者电邮,如果没有发现已经存在的数据，返回FALSE
     * @param type $userInfo
     * @return boolean
     */
    public function haveExistUserInfo($userInfo) {
        $mobile = NULL;
        $email = NULL;
        $checkedResult = array();
        if (is_numeric($userInfo) && $userInfo != NULL) {
            $mobile = $userInfo;
        }
        if (is_string($userInfo) && $userInfo != NULL) {
            $email = $userInfo;
        }
        if (is_array($userInfo)) {
            if (isset($userInfo['mobile']))
                $mobile = $userInfo['mobile'];
            if (isset($userInfo['email']))
                $email = $userInfo['email'];
        }

        $userInfoTable = new BAUserSheet('userInfo');
        if ($mobile != NULL) {
            $list = $userInfoTable->getList(array('itemData' => array('mobile' => $mobile)));
            if ($list != NULL) {
                $checkedResult['mobile'] = $mobile;
            }
        }
        if ($email != NULL) {
            $list = $userInfoTable->getList(array('itemData' => array('email' => $email)));
            if ($list != NULL) {
                $checkedResult['email'] = $email;
            }
        }

        if ($checkedResult != NULL) {
            return $checkedResult;
        }

        return FALSE;
    }

    /**
     * 这个函数用来获取当前APP下面的用户数据。对比邻平台来说，有2组用户数据，一组是平台的用户数据，一组是
     * 每个APP的用户数据，分别放在BUserSheet和BAUserSheet里面
     * 
     * @param type $itemContext,当没有参数的时候，将取出当前用户的手机或者电邮地址，然后去查找当前APP下面的
     * 用户数据
     * @return BList
     */
    /*
      public function getUserInfo($itemContext = NULL, $format = 'treeList') {
      if ($itemContext == NULL) {
      $itemContext = Blyn::app()->getCurrentUser();
      }
      $userInfoTable = new BAUserSheet('userInfo');
      if (is_numeric($itemContext) && $itemContext > 0) {
      return $userInfoTable->getListById($itemContext);
      }
      $userContext = array();
      if ($itemContext instanceof BUser) {
      $user = $itemContext;
      $mobileAttr = $user->getAttribute('userInfo.mobile');
      if ($mobileAttr != NULL && $mobileAttr->getValue() != NULL) {
      $userContext['mobile'] = $mobileAttr->getValue();
      }
      $emailAttr = $user->getAttribute('userInfo.email');
      if ($emailAttr != NULL) {
      $email = $emailAttr->getValue();
      if ($email != NULL) {
      $userContext['email'] = $email;
      }
      }
      }

      if ($userContext == NULL) {
      return FALSE;
      }


      if (is_array($itemContext) && $itemContext != NULL) {
      $searchContext = array();
      if (isset($itemContext['userId'])) {
      $searchContext['userId'] = $itemContext['userId'];
      $oUserInfo = $userInfoTable->getList(array('itemData' => $searchContext));
      if ($userInfo != NULL)
      return $oUserInfo;
      }
      if (isset($itemContext['mobile'])) {
      $searchContext['mobile'] = $itemContext['mobile'];
      $oUserInfo = $userInfoTable->getList(array('itemData' => $searchContext));
      if ($userInfo != NULL)
      return $oUserInfo;
      }
      if (isset($itemContext['email'])) {
      $searchContext['email'] = $itemContext['email'];
      $oUserInfo = $userInfoTable->getList(array('itemData' => $searchContext));
      if ($userInfo != NULL)
      return $oUserInfo;
      }
      }

      if ($userContext != NULL) {

      $oUserInfo = NULL;
      $aUserInfo = array();
      if (isset($userContext['userId']) && $userContext['userId'] != NULL) {
      $oUserInfo = $userInfoTable->getList(array('itemData' => array('userId' => $userContext['userId'])));
      }
      if ($oUserInfo == NULL && isset($userContext['mobile']) && $userContext['mobile'] != NULL) {
      $oUserInfo = $userInfoTable->getList(array('itemData' => array('mobile' => $userContext['mobile'])));
      }
      if ($oUserInfo == NULL && isset($userContext['email']) && $userContext['email'] != NULL) {
      $oUserInfo = $userInfoTable->getList(array('itemData' => array('email' => $userContext['email'])));
      }
      if ($format == 'array') {
      if ($oUserInfo != NULL)
      return $oUserInfo->getItemsInArray();
      else {
      //可以将平台个人数据里面取得的数据返回
      return $userContext;
      }
      }
      return $oUserInfo;
      }
      return FALSE;
      }
     * 
     */

    /**
     * this function will return user object according itemContext
     * it will find user by below logic:
     * 1)by userId
     * 2)by mobile, if provide mobile, will search userInfo table to find userId
     * by mobile
     * 3)by email, if provice email, will search userInfo table to find userId 
     * by email
     * @param type $itemContex
     */
    public function getUserByInfo($userInfo = NULL) {

        $userId = NULL;

        if ($userInfo instanceof BUser)
            return $userInfo;

        if ($userInfo == NULL)
            return Blyn::app()->getCurrentUser();

        if (is_numeric($userInfo) && $userInfo > 0) {
            $userId = $userInfo;
            return new BUser($userId);
        }

        if (is_array($userInfo)) {
            if (isset($userInfo['userId'])) {
                $userId = $userInfo['userId'];
                if ($userId > 0)
                    return new BUser($userId);
            }
        }

//find if userInfo contain userId
        $oUserInfo = $this->getUserInfo($userInfo);
        if ($oUserInfo != NULL) {
            $userIdItem = $oUserInfo->getItem('userId');
            if ($userIdItem != NULL) {
                $userId = $userIdItem->getValue();
                if ($userId > 0) {
                    return new BUser($userId);
                }
            }
        }

//find by mobile
        if (isset($userInfo['mobile'])) {
            $mobile = $userInfo['mobile'];
            $userInfoTable = new BUserSheet('userInfo');
            $list = $userInfoTable->getList(array('itemData' => array('mobile' => $mobile)));
            if ($list != NULL) {
                $userIdItem = $list->getItem('userId');
                if ($userIdItem != NULL) {
                    $userId = $userIdItem->getValue();
                    if ($userId > 0) {
                        return new BUser($userId);
                    }
                }
            }
        }

//find by email
        if (isset($userInfo['email'])) {
            $email = $userInfo['email'];
            $userInfoTable = new BUserSheet('userInfo');
            $list = $userInfoTable->getList(array('itemData' => array('email' => $email)));
            if ($list != NULL) {
                $userIdItem = $list->getItem('userId');
                if ($userIdItem != NULL) {
                    $userId = $userIdItem->getValue();
                    if ($userId > 0) {
                        return new BUser($userId);
                    }
                }
            }
        }

        return FALSE;
    }

    /**
     * 打开添加用户信息的页面，很多情况下，添加用户信息是再别的页面之中
     * 去操作的,可以用这个函数在别的页面中嵌入添加个人信息页面
     * 这个函数将调用THEME根目录下的user_add_info，所以control
     * 必须是BUIThemed control或者BUIControl，不能是BUIEventControl
     */
    public function showAddUserInfo($control = NULL, $aViewData = array()) {
        
    }

    /**
     * 用户调用这个函数来显示个人信息的绑定页面，它和用户信息添加页面不同，
     * 用户信息添加页面是机构管理员添加用户用的
     * @param type $control
     * @param type $aViewData
     */
    public function showBindUserInfo($parentControl = NULL, $aViewData = array()) {

        $control = new BUIThemedControl('bindUserInfo');

        $model = new BDynamicFormModel();
        $mobileField = 'media_mobile_add_userInfo';
        $openidField = 'media_openid_add_userInfo';
        $emailField = 'media_email_add_userInfo';
        $genderField = 'media_gender_add_userInfo';
        $familyNameField = 'media_familyName_add_userInfo';
        $surNameField = 'media_surName_add_userInfo';
        $birthField = 'media_birth_add_userInfo';
        $model->addField($mobileField);
        $model->addField($openidField);
        $model->addField($emailField);
        $model->addField($genderField);
        $model->addField($familyNameField);
        $model->addField($surNameField);
        $model->addField($birthField);

        //获取当前用户的用户信息
        $oUserInfo = $this->getUserInfo();

        if ($oUserInfo != NULL) {
            $userInfo = $oUserInfo->getItemsInArray();

            if (isset($userInfo['mobile'])) {
                $model->$mobileField = $userInfo['mobile'];
            }
            if (isset($userInfo['openid'])) {
                $model->$openidField = $userInfo['openid'];
            }
            if (isset($userInfo['email'])) {
                $model->$emailField = $userInfo['email'];
            }
            if (isset($userInfo['gender'])) {
                $model->$genderField = $userInfo['gender'];
            }
            if (isset($userInfo['familyName'])) {
                $model->$familyNameField = $userInfo['familyName'];
            }
            if (isset($userInfo['surName'])) {
                $model->$surNameField = $userInfo['surName'];
            }
            if (isset($userInfo['birth'])) {
                $model->$birthField = $userInfo['birth'];
            }
        }

        /**
         * 将上一次的数据传递下去
         */
        if ($aViewData != NULL) {
            if (isset($aViewData['mobile'])) {
                $model->$mobileField = $aViewData['mobile'];
            }
            if (isset($aViewData['openid'])) {
                $model->$openidField = $aViewData['openid'];
            }
            if (isset($aViewData['email'])) {
                $model->$emailField = $aViewData['email'];
            }
            if (isset($aViewData['gender'])) {
                $model->$genderField = $aViewData['gender'];
            }
            if (isset($aViewData['familyName'])) {
                $model->$familyNameField = $aViewData['familyName'];
            }
            if (isset($aViewData['surName'])) {
                $model->$surNameField = $aViewData['surName'];
            }
            if (isset($aViewData['birth'])) {
                $model->$birthField = $aViewData['birth'];
            }
        }

        $viewData = array();
        $viewData['model'] = $model;
        $viewData['mobileField'] = $mobileField;
        $viewData['openidField'] = $openidField;
        $viewData['emailField'] = $emailField;
        $viewData['familyNameField'] = $familyNameField;
        $viewData['surNameField'] = $surNameField;
        $viewData['genderField'] = $genderField;
        $viewData['birthField'] = $birthField;
        if ($aViewData != NULL) {
            $viewData+=$aViewData;
        }

        $control->addRenderView('bindUserInfo', 'user_info_bind', $viewData);

        if ($parentControl instanceof BUIControl) {
            $parentControl->addChildControl($control);
        } else {
            $control->render();
        }
    }

    public function onBindUserInfo() {
        $postData = $this->postManager->populatePostDataByIndex($this->postData, 'add_userInfo');

        $oUserInfo = $this->getUserInfo();

        if ($oUserInfo != NULL) {
            $userData = $oUserInfo->getItemsInArray();
            $postData = $userData + $postData;
        }

        $ret = $this->bindUserInfo($postData);

        if ($ret instanceof BAError) {
            $errorMessages = $ret->getErrorMessages();
            $errorMessages+=$postData;
            $this->showBindUserInfo($this->updateControl, $errorMessages);
            return;
        } else {
            /*
              $oUserInfo = $ret;
              $this->updateControl->addRenderView('displayUserInfo', 'user_info_display', array('userInfo' => $oUserInfo));
             * 
             */
        }

        $this->showBindUserInfo($this->updateControl, array('message' => 'add user info successfully!'));
    }

    public function onShowChangeUserPassword() {
        $this->updateControl->addRenderView('changeUserPassword');
    }

    public function onSaveUserPassword() {
        $user = Blyn::app()->getCurrentUser();
        $postManager = new BPostManager();
        $postData = $postManager->parsedModelData();
        $mediaList = $postManager->populateMediaListFromPostData($postData, 'userPassword');

        $oldPwd = $mediaList['password']->getContent();
        $newPwd = $mediaList['password1']->getContent();
        $confirmedPwd = $mediaList['password2']->getContent();

        $weChatAttr = $user->getAttribute('wxOpenId');
        if ($weChatAttr) {
            $openId = $weChatAttr->getValue();
            $oldPwd = $openId;
            $pwdAttr = $user->getAttribute('changedWechatPassword');
            if ($pwdAttr) {
                $oldPwd = $pwdAttr->getValue();
            }
        }

        if ($newPwd == $confirmedPwd) {
            $attributes = array();
            $attributes['password'] = $newPwd;
            $isChangedPassword = $user->save($attributes);
//                $isChangedPassword = $user->changePassword($oldPwd, $newPwd);
        }

        if (isset($isChangedPassword) && $isChangedPassword) {
            $updateControl->addRenderView('changedPassword', 'changeUserPassword', array(
                'isChangedPassword' => 'success'));
        } else {
            $updateControl->addRenderView('changeUserPassword', 'changeUserPassword', array(
                'isChangedPassword' => 'fail'));
        }
    }

    public function onShowUserInfo() {
        
    }

    public function onShowAddUserInfo() {
        
    }

    /**
     * this function use in view to render addUserInfo view
     * @param BUIThemedControl $control
     * @param type $aViewData
     */
    /*
      public function renderAddUserInfo($control = NULL, $aViewData = array()) {
      if ($control == NULL) {
      $control = new BUIThemedControl('addUserInfo');
      }

      $model = new BDynamicFormModel();
      $mobileField = 'media_mobile_add_userInfo';
      $emailField = 'media_email_add_userInfo';
      $genderField = 'media_gender_add_userInfo';
      $familyNameField = 'media_familyName_add_userInfo';
      $surNameField = 'media_surName_add_userInfo';
      $birthField = 'media_birth_add_userInfo';
      $model->addField($mobileField);
      $model->addField($emailField);
      $model->addField($genderField);
      $model->addField($familyNameField);
      $model->addField($surNameField);
      $model->addField($birthField);

      $userInfo = $this->getUserInfo(null, 'array');

      if ($userInfo != NULL) {
      if (isset($userInfo['mobile'])) {
      $model->$mobileField = $userInfo['mobile'];
      }
      if (isset($userInfo['email'])) {
      $model->$emailField = $userInfo['email'];
      }
      if (isset($userInfo['gender'])) {
      $model->$genderField = $userInfo['gender'];
      }
      if (isset($userInfo['familyName'])) {
      $model->$familyNameField = $userInfo['familyName'];
      }
      if (isset($userInfo['surName'])) {
      $model->$surNameField = $userInfo['surName'];
      }
      if (isset($userInfo['birth'])) {
      $model->$birthField = $userInfo['birth'];
      }
      }

      $viewData = array();
      $viewData['model'] = $model;
      $viewData['mobileField'] = $mobileField;
      $viewData['emailField'] = $emailField;
      $viewData['familyNameField'] = $familyNameField;
      $viewData['surNameField'] = $surNameField;
      $viewData['genderField'] = $genderField;
      $viewData['birthField'] = $birthField;
      if ($aViewData != NULL) {
      $viewData+=$aViewData;
      }

      $control->addRenderView('addUserInfo', 'user_info_add', $viewData);
      $control->render();
      }
     * 
     */

    public function onAddUserInfo() {

        $postData = $this->postManager->populatePostDataByIndex($this->postData, 'add_userInfo');

        $userInfo = $this->addUserInfo($postData);

        $this->updateControl->addRenderView('addUserInfo', 'user_info_add', array('userInfo' => $userInfo));

        /*

          $userData = $this->getUserInfo(NULL, 'array');

          //将POSTData里面没有的数据补充进去
          if (is_array($userData))
          $postData = $userData + $postData;

          $ret = $this->addUserInfo($postData);

          if ($ret instanceof BAError) {
          //$viewData=array();
          $errorMessages = $ret->getErrorMessages();
          $errorMessages+=$postData;
          $this->showAddUserInfo($this->updateControl, $errorMessages);
          return;
          } else {

          $oUserInfo = $ret;
          $this->updateControl->addRenderView('displayUserInfo', 'user_info_display', array('userInfo' => $oUserInfo));

          }
         * 
         */

        //$this->showAddUserInfo($this->updateControl, array('message' => 'add user info successfully!'));
    }

    public static function getGenderData() {
        return array(
            'lady' => '女士',
            'mister' => '先生',
            'boy' => '男孩',
            'girl' => '女孩'
        );
    }

    public static function getGenderAlias($gender) {
        if (strtolower($gender) == 'lady')
            return '女士';
        if (strtolower($gender) == 'mister')
            return '先生';
        if (strtolower($gender) == 'boy')
            return '男孩';
        if (strtolower($gender) == 'girl')
            return '女孩';
    }

    /**
      public function getGlobalUserInfo($userData = NULL) {

      $userInfoTable = new BUserSheet('userInfo');

      if ($userData == NULL) {//查找当前用户的平台用户数据
      $mobileAttr = Blyn::app()->getCurrentUser()->getAttribute('userInfo.mobile');
      if ($mobileAttr != NULL) {
      $mobile = $mobileAttr->getValue();
      if ($mobile != NULL) {
      $itemContext = array();
      $itemContext['mobile'] = $mobile;
      return $userInfoTable->getList(array('itemData' => $itemContext));
      }
      }
      } else {
      if (isset($userData['userId'])) {//提供用户Id查找客户
      $itemContext = array('userId' => $userData['userId']);
      return $userInfoTable->getList(array('itemData' => $itemContext));
      }
      if (isset($userData['mobile'])) {//提供手机号查找用户
      $itemContext = array('mobile' => $userData['mobile']);
      return $userInfoTable->getList(array('itemData' => $itemContext));
      }
      if (isset($userData['email'])) {//提供EMAIL查找用户
      $itemContext = array('email' => $userData['email']);
      return $userInfoTable->getList(array('itemData' => $itemContext));
      }
      }

      return FALSE;
      }
     * 
     * @param type $userData
     * @return boolean
     */
    public function getUserInfo($userData = NULL) {
        if ($userData instanceof BTreeList)
            return $userData;

        $userInfoTable = new BAUserSheet('userInfo');

        if ($userData instanceof BUser) {
            $user = $userData;
            $oUserInfo = $userInfoTable->getList(array('itemData' => array('userId' => $user->getId())));
            if ($oUserInfo != NULL) {
                return $oUserInfo;
            }
        }

        if ($userData == NULL) {//查找当前用户的平台用户数据
            $user = Blyn::app()->getCurrentUser();
            $oUserInfo = $userInfoTable->getList(array('itemData' => array('userId' => $user->getId())));
            if ($oUserInfo != NULL) {
                return $oUserInfo;
            }
            $mobileAttr = Blyn::app()->getCurrentUser()->getAttribute('userInfo.mobile');
            if ($mobileAttr != NULL) {
                $mobile = $mobileAttr->getValue();
                if ($mobile != NULL) {
                    $itemContext = array();
                    $itemContext['mobile'] = $mobile;
                    return $userInfoTable->getList(array('itemData' => $itemContext));
                }
            }
        } else {
            if (is_numeric($userData)) {
                return $this->getUserInfoById($userData);
            }
            if (is_array($userData)) {
                if (isset($userData['userInfoId'])) {
                    return $this->getUserInfoById($userData['userInfoId']);
                }
                if (isset($userData['userId'])) {//提供用户Id查找客户
                    $itemContext = array('userId' => $userData['userId']);
                    $oUserInfo = $userInfoTable->getList(array('itemData' => $itemContext));
                    if ($oUserInfo != NULL) {
                        return $oUserInfo;
                    }
                }
                if (isset($userData['mobile'])) {//提供手机号查找用户
                    $itemContext = array('mobile' => $userData['mobile']);
                    $oUserInfo = $userInfoTable->getList(array('itemData' => $itemContext));
                    if ($oUserInfo != NULL) {
                        return $oUserInfo;
                    }
                }
                if (isset($userData['email'])) {//提供EMAIL查找用户
                    $itemContext = array('email' => $userData['email']);
                    $oUserInfo = $userInfoTable->getList(array('itemData' => $itemContext));
                    if ($oUserInfo != NULL) {
                        return $oUserInfo;
                    }
                }
            }
        }

        return FALSE;
    }

    public function getUserInfoById($id) {
        $userInfoTable = new BAUserSheet('userInfo');
        return $userInfoTable->getListById($id);
    }

    /**
      public function addSpaceUserInfo($userData, $alsoAddGlobal = TRUE) {
      $spaceUserInfoTable = new BAUserSheet('userInfo');
      $oUserInfo = $this->getSpaceUserInfo($userData);
      $error = new BAError();

      if ($gUserInfo == NULL && $oUserInfo == NULL) {
      //平台和机构个人信息都不存在
      if (!isset($userData['mobile'])) {
      $error->addError('必须提供手机号', 'wrongMobile');
      return $error;
      }

      $spaceUserInfoTable->addList($userData);
      $userInfoTable->addList($userData);
      }

      //只存在平台用户数据
      if ($gUserInfo != NULL && $oUserInfo == NULL) {
      $gUserData = $gUserInfo->getItemsInArray();
      $gUserData = $userData + $gUserData;
      //补充平台用户数据里面没有的数据
      $gUserInfo->addItems($gUserData);
      //新加机构数据
      $spaceUserInfoTable->addList($userData);
      }

      //只存在机构数据
      if ($gUserInfo == NULL && $oUserInfo != NULL) {
      //修改机构数据
      $oUserInfo->addItems($userData);
      //新加平台数据
      $UserInfoTable->addList($userData);
      }
      }
     * 
     * @param type $userData
     */
    /**
      public function addGlobalUserInfo($userData) {
      $userInfoTable = new BUserSheet('userInfo');
      //只有本人可以修改平台用户数据
      $oUserInfo = $this->getGlobalUserInfo();
      $error = new BAError();

      if (is_array($userData) && $userData != NULL) {
      if ($oUserInfo == NULL) {//说明用户没有注册平台用户信息
      //先检查是否存在已有用户，如果存在，返回用户已存在信息
      $existUserInfo = $this->getGlobalUserInfo($userData);
      if ($existUserInfo != NULL) {
      $existUserData = $existUserInfo->getItemsInArray();
      if (isset($existUserData['mobile'])) {
      $error->addError('手机号已经被使用，请用别的手机号', 'wrongMobile');
      }
      if (isset($existUserData['email'])) {
      $error->addError('EMAIL已经被使用，请用别的EMAIL', 'wrongEmail');
      }
      } else {//没有用户使用提供的信息，可以放心添加信息
      $userInfoTable->addList($userData);
      }
      } else {//本人已经有平台数据，更新平台数据即可
      //检查是否存在已有用户，如果存在，返回用户已存在信息
      //如果提供的手机号，email没有被使用，那么可以用来更新平台用户数据
      //改变平台用户数据，可能导致机构用户数据的不一致，那么，需要通过
      //更新机构用户数据来保持一致
      $existUserInfo = $this->getGlobalUserInfo($userData);
      if ($existUserInfo != NULL) {
      $existUserData = $existUserInfo->getItemsInArray();
      if (isset($existUserData['mobile'])) {
      $error->addError('手机号已经被使用，请用别的手机号', 'wrongMobile');
      }
      if (isset($existUserData['email'])) {
      $error->addError('EMAIL已经被使用，请用别的EMAIL', 'wrongEmail');
      }
      } else {//没有用户使用提供的信息，可以放心添加信息
      $oUserInfo->addItems($userData);
      }
      }
      }
      }
     * 
     */

    /**
     * 这个函数用来将用户和机构个人信息绑定，使用的情形包括：
     * 1）用户进入某机构，如果通过userData发现已经有机构个人数据，
     * 那么将用户的id加入记录，表明用户已经绑定，
     * 2）用户进入某机构，如果没有发现机构个人数据，那么创建机构个人数据
     * 并将用户id加入记录实现绑定
     * 3）用户在某个机构里面修改个人信息的时候，也用这个函数来更新用户信息
     * @param type $spaceUserInfo
     * @param type $data
     */
    public function bindUserInfo($userData, $data = NULL) {

        $userInfoTable = new BAUserSheet('userInfo');
        $error = new BAError();

        $oUserInfo = $this->getUserInfo($userData);
        $user = Blyn::app()->getCurrentUser();

        if (is_array($userData) && $userData != NULL) {
            if ($oUserInfo == NULL) {//在机构里面没有个人数据
                //那么添加个人数据
                $userData['userId'] = Blyn::app()->getCurrentUser()->getId();
                return $userInfoTable->addList($userData);
            } else {//说明已经有对应的个人信息
                $oldUserData = $oUserInfo->getItemsInArray();
                if (isset($oldUserData['userId'])) {
                    //检查是否已经被别的用户使用
                    if ($oldUserData['userId'] != $user->getId()) {
                        $error->addError('添加用户信息失败');
                        if (isset($oldUserData['mobile'])) {
                            if (isset($userData['mobile'])) {
                                if ($oldUserData['mobile'] == $userData['mobile'])
                                    $error->addError('手机号已经被使用', 'wrongMobile');
                            }
                        }
                        if (isset($oldUserData['email'])) {
                            if (isset($userData['email'])) {
                                if ($oldUserData['email'] == $userData['email'])
                                    $error->addError('EMAIL已经被使用', 'wrongEmail');
                            }
                        }
                        return $error;
                    }
                }
                $userData = $oldUserData + $userData;
                $userData['userId'] = Blyn::app()->getCurrentUser()->getId();
                return $oUserInfo->addItems($userData);
            }
        }

        return FALSE;
    }

    /**
     * 这个函数用来创建和修改机构个人信息，这个个人信息可以绑定或者不绑定
     * @param type $userData
     */
    public function addUserInfo($userData) {

        $userInfoTable = new BAUserSheet('userInfo');

        if (is_array($userData)) {
            if (isset($userData['birth'])) {
                $birth = $userData['birth'];
                $tBirth = strtotime($birth);
                //格式化生日为统一格式
                $dBirth = date('Ymd', $tBirth);
                $userData['birth'] = $dBirth;
            }
            $oUserInfo = $this->getUserInfo($userData);

            if ($oUserInfo == NULL) {
                return $userInfoTable->addList($userData);
            } else {
                return $oUserInfo->addItems($userData);
            }
        }

        return FALSE;
    }

    public function getAllUsersWithinBirthSpan($timeSpan) {

        $userInfoTable = new BAUserSheet('userInfo');

        //birth format must be 'Ymd'
        $startTime = strtotime('- ' . $timeSpan);
        $endTime = strtotime('+' . $timeSpan);
        $startDay = date('Ymd', $startTime);
        $endDay = date('Ymd', $endTime);

        $view = $userInfoTable->getView(array('itemData' => array(
                'birth&' => array('<' . $endDay, '>' . $startDay)
        )));

        return $view;
    }

}
